package tk.winshu.shortestpath.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.winshu.shortestpath.model.Node;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jason Krebs
 * @date 2015年2月7日
 */
public class ImportUtil {

    private static final Logger log = LoggerFactory.getLogger(ImportUtil.class.getName());
    private static final String NODE_TAG = "node";
    private static final String LINE_TAG = "line";

    /**
     * 导入Node信息
     */
    public static List<Node> importFrom(String path, Image image) {
        List<Node> nodes = new ArrayList<>();

        String data = FileUtil.loadFrom(path);
        if (data == null || data.isEmpty()) {
            return nodes;
        }

        JSONObject object = JSONObject.parseObject(data);

        JSONArray nodeArray = object.getJSONArray(NODE_TAG);
        Map<Integer, Node> nodesMap = parseNode(nodeArray);

        JSONArray lineArray = object.getJSONArray(LINE_TAG);
        nodes.addAll(parseLine(lineArray, nodesMap));

        for (Node node : nodes) {
            node.setImage(image);
        }

        return nodes;
    }

    private static List<Node> parseLine(JSONArray lineArray, Map<Integer, Node> nodesMap) {
        List<Node> nodes = new ArrayList<>();
        if (lineArray == null) {
            return nodes;
        }
        for (int i = 0; i < lineArray.size(); i++) {
            JSONObject line = lineArray.getJSONObject(i);

            int start = line.getIntValue("start");
            int end = line.getIntValue("end");

            Node startNode = nodesMap.get(start);
            Node endNode = nodesMap.get(end);

            if (startNode == null || endNode == null) {
                continue;
            }
            startNode.addEndNode(endNode);
            endNode.addStartNode(startNode);
        }
        nodes.addAll(nodesMap.values());

        return nodes;
    }

    private static Map<Integer, Node> parseNode(JSONArray nodeArray) {
        Map<Integer, Node> nodes = new HashMap<>();
        for (int i = 0; i < nodeArray.size(); i++) {
            JSONObject nodeObject = nodeArray.getJSONObject(i);
            Node node = JSONObject.parseObject(nodeObject.toJSONString(), Node.class);
            if (node != null) {
                nodes.put(node.getIndex(), node);
            }
        }
        log.info(String.format("节点数量：%d", nodes.size()));
        return nodes;
    }
}
